const constants   = require('../../data/constants');
const deviceModel = require('../../model/device');
const sipServer   = require('../../sip/server');
let Device={

    /**
     * API接口，获取设备列表
     * @param {*} req 
     * @param {*} res 
     */
    list: async function (req, res){
      let page = req.query.page;
      let pagesize = req.query.pagesize;
      if(typeof(page)=='undefined') page=1;
      if(!pagesize) pagesize=10000;

      let count = await deviceModel.count();
      deviceModel.list(page-1, pagesize).then((rows)=>{
          let ret =Object.assign(constants.httpCode.OK , {data:{items:rows, total:count, page:page, pagesize:pagesize}});
          res.send(ret);
      });
    },
    /**
     * Query接口读取一个摄像头信息
     * @param {*} req 
     * @param {*} res 
     */
    query:function(req,res){
      let deviceid = req.query.deviceid;

      deviceModel.getDeviceByDeviceId(deviceid,(ret)=>{
        if(ret.length){
          let send =Object.assign(constants.httpCode.OK , {data:{items:ret,total:ret.length}});
          res.send(send);
        }else{
          let send =Object.assign(constants.httpCode.NO_DATA , {data:null});
          res.send(send);
        }
      });
    },
    /**
     * 请求目录
     * @param {*} req 
     * @param {*} res 
     */
    catalog:function(req,res){
      let account = req.query.account;
      sipServer.catalog(account);
      let ret =Object.assign(constants.httpCode.OK , {data:{}});
      res.send(ret);
    },
    deldevice:function(req,res){
      deviceModel.del(req.body.account);
      // 删除缓存信息
      if(constants.registry && constants.registry[req.body.account]){
        delete constants.registry[req.body.account];
      }
      let ret =Object.assign(constants.httpCode.OK , {data:{}});
      res.send(ret);
    },
    /**
     * 更新通道名称
     * @param {*} req 
     * @param {*} res 
     */
    updatename:function(req,res){
      deviceModel.update({
        deviceid: req.body.deviceid,
        device_name: req.body.device_name
      });
      let ret =Object.assign(constants.httpCode.OK , {data:{}});
      res.send(ret);
    }
};

module.exports=Device;